"use client"

import React, { useState, useEffect } from 'react'
import { AdminLayout } from '@/components/layout/admin-layout'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Modal } from '@/components/ui/modal'
import { useRouter } from 'next/navigation'
import {
  Users,
  UserCheck,
  FileText,
  Briefcase,
  TrendingUp,
  Clock,
  Eye,
  Heart,
  Bell,
  Settings
} from 'lucide-react'
import { adminAPI, type DashboardStats, type User } from '@/lib/api'
import { formatNumber, formatDateTime } from '@/lib/utils'

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null)
  const [recentUsers, setRecentUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const [showDetailReport, setShowDetailReport] = useState(false)
  const router = useRouter()

  // 导航处理器
  const handleNavigation = (path: string) => {
    router.push(path)
  }

  // 显示通知
  const showNotification = (message: string) => {
    alert(message)
  }

  // 显示详细报告
  const showDetailedReport = () => {
    setShowDetailReport(true)
  }

  useEffect(() => {
    const loadData = async () => {
      try {
        const [statsData, usersData] = await Promise.all([
          adminAPI.getDashboardStats(),
          adminAPI.getRecentUsers(5)
        ])
        setStats(statsData)
        setRecentUsers(usersData)
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        setLoading(false)
      }
    }

    loadData()
  }, [])

  const statsCards = [
    {
      title: '总用户数',
      value: stats?.totalUsers || 0,
      icon: Users,
      color: 'text-blue-600',
      bgColor: 'bg-blue-100',
    },
    {
      title: '活跃用户',
      value: stats?.activeUsers || 0,
      icon: UserCheck,
      color: 'text-green-600',
      bgColor: 'bg-green-100',
    },
    {
      title: '文章总数',
      value: stats?.totalNews || 0,
      icon: FileText,
      color: 'text-amber-600',
      bgColor: 'bg-amber-100',
    },
    {
      title: '商业计划书',
      value: stats?.totalPlans || 0,
      icon: Briefcase,
      color: 'text-purple-600',
      bgColor: 'bg-purple-100',
    },
  ]

  if (loading) {
    return (
      <AdminLayout>
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-gray-900">仪表板</h1>
          </div>
          <div className="text-center py-12">加载中...</div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Page Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">仪表板</h1>
            <p className="text-gray-600">系统概览和关键指标</p>
          </div>
          <Button onClick={() => showDetailedReport()}>
            <TrendingUp className="h-4 w-4 mr-2" />
            查看详细报告
          </Button>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {statsCards.map((stat) => {
            const Icon = stat.icon
            return (
              <Card key={stat.title} className="hover:shadow-lg transition-shadow">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm font-medium text-gray-600">{stat.title}</p>
                      <p className="text-2xl font-bold text-gray-900">{formatNumber(stat.value)}</p>
                    </div>
                    <div className={`p-3 rounded-full ${stat.bgColor}`}>
                      <Icon className={`h-6 w-6 ${stat.color}`} />
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        {/* Recent Users */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Users className="h-5 w-5" />
                <span>最近注册用户</span>
              </div>
              <Button variant="outline" size="sm" onClick={() => handleNavigation('/users')}>
                查看全部
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {recentUsers.length > 0 ? (
                recentUsers.map((user) => (
                  <div key={user.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-4">
                      <div className="w-10 h-10 bg-slate-600 text-white rounded-full flex items-center justify-center">
                        <span className="text-sm font-medium">
                          {user.name ? user.name.charAt(0) : user.username.charAt(0)}
                        </span>
                      </div>
                      <div>
                        <h4 className="font-medium text-gray-900">{user.name || user.username}</h4>
                        <p className="text-sm text-gray-500">{user.email}</p>
                        {user.company && (
                          <p className="text-xs text-gray-400">{user.company}</p>
                        )}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                        user.status === 1 
                          ? 'bg-green-100 text-green-800' 
                          : 'bg-red-100 text-red-800'
                      }`}>
                        {user.status === 1 ? '正常' : '禁用'}
                      </div>
                      <p className="text-xs text-gray-500 mt-1">
                        {formatDateTime(user.createdAt)}
                      </p>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center py-8 text-gray-500">
                  暂无用户数据
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* System Info */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Clock className="h-5 w-5" />
                <span>系统信息</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="flex justify-between">
                  <span className="text-gray-600">服务器时间</span>
                  <span className="font-mono text-sm">{formatDateTime(new Date())}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">数据库状态</span>
                  <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                    正常
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">Spring Boot</span>
                  <span className="text-sm">2.2.6.RELEASE</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">系统运行</span>
                  <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                    正常
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <TrendingUp className="h-5 w-5" />
                <span>快速操作</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-3">
                <Button variant="outline" className="h-16 flex-col" onClick={() => handleNavigation('/users')}>
                  <Users className="h-5 w-5 mb-1" />
                  <span className="text-xs">管理用户</span>
                </Button>
                <Button variant="outline" className="h-16 flex-col" onClick={() => handleNavigation('/news')}>
                  <FileText className="h-5 w-5 mb-1" />
                  <span className="text-xs">内容管理</span>
                </Button>
                <Button variant="outline" className="h-16 flex-col" onClick={() => handleNavigation('/business-plans')}>
                  <Briefcase className="h-5 w-5 mb-1" />
                  <span className="text-xs">商业计划</span>
                </Button>
                <Button variant="outline" className="h-16 flex-col" onClick={() => handleNavigation('/settings')}>
                  <TrendingUp className="h-5 w-5 mb-1" />
                  <span className="text-xs">系统设置</span>
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Detailed Report Modal */}
        <Modal
          isOpen={showDetailReport}
          onClose={() => setShowDetailReport(false)}
          title="系统详细报告"
          size="xl"
          footer={
            <div className="flex justify-end space-x-2">
              <Button variant="outline" onClick={() => setShowDetailReport(false)}>
                关闭
              </Button>
              <Button onClick={() => alert('导出功能开发中...')}>
                导出报告
              </Button>
            </div>
          }
        >
          <div className="space-y-6">
            {/* 系统概览 */}
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">系统概览</h3>
              <div className="grid grid-cols-2 gap-4">
                <div className="bg-blue-50 p-4 rounded-lg">
                  <div className="text-sm text-blue-600 font-medium">总用户数</div>
                  <div className="text-2xl font-bold text-blue-900">{formatNumber(stats?.totalUsers || 0)}</div>
                  <div className="text-sm text-blue-600">较上月增长 12.5%</div>
                </div>
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="text-sm text-green-600 font-medium">活跃用户</div>
                  <div className="text-2xl font-bold text-green-900">{formatNumber(stats?.activeUsers || 0)}</div>
                  <div className="text-sm text-green-600">较上月增长 8.3%</div>
                </div>
                <div className="bg-purple-50 p-4 rounded-lg">
                  <div className="text-sm text-purple-600 font-medium">文章总数</div>
                  <div className="text-2xl font-bold text-purple-900">{formatNumber(stats?.totalNews || 0)}</div>
                  <div className="text-sm text-purple-600">较上月增长 15.2%</div>
                </div>
                <div className="bg-amber-50 p-4 rounded-lg">
                  <div className="text-sm text-amber-600 font-medium">商业计划书</div>
                  <div className="text-2xl font-bold text-amber-900">{formatNumber(stats?.totalPlans || 0)}</div>
                  <div className="text-sm text-amber-600">较上月增长 22.1%</div>
                </div>
              </div>
            </div>

            {/* 用户分析 */}
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">用户分析</h3>
              <div className="bg-gray-50 p-4 rounded-lg">
                <div className="grid grid-cols-3 gap-4 text-center">
                  <div>
                    <div className="text-sm text-gray-600">新注册用户</div>
                    <div className="text-xl font-bold text-gray-900">245</div>
                    <div className="text-sm text-green-600">↗ +18.2%</div>
                  </div>
                  <div>
                    <div className="text-sm text-gray-600">用户留存率</div>
                    <div className="text-xl font-bold text-gray-900">78.5%</div>
                    <div className="text-sm text-green-600">↗ +2.1%</div>
                  </div>
                  <div>
                    <div className="text-sm text-gray-600">平均会话时长</div>
                    <div className="text-xl font-bold text-gray-900">12.4分钟</div>
                    <div className="text-sm text-blue-600">↗ +5.3%</div>
                  </div>
                </div>
              </div>
            </div>

            {/* 内容统计 */}
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">内容统计</h3>
              <div className="space-y-3">
                <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                  <span className="text-gray-700">创业资讯文章</span>
                  <span className="font-semibold">156篇</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                  <span className="text-gray-700">政策解读文章</span>
                  <span className="font-semibold">89篇</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                  <span className="text-gray-700">投融资资讯</span>
                  <span className="font-semibold">67篇</span>
                </div>
                <div className="flex justify-between items-center p-3 bg-gray-50 rounded">
                  <span className="text-gray-700">科技创新文章</span>
                  <span className="font-semibold">42篇</span>
                </div>
              </div>
            </div>

            {/* 系统状态 */}
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">系统状态</h3>
              <div className="grid grid-cols-4 gap-4">
                <div className="text-center">
                  <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-2">
                    <div className="w-4 h-4 bg-green-500 rounded-full"></div>
                  </div>
                  <div className="text-sm font-medium">服务器状态</div>
                  <div className="text-xs text-green-600">正常运行</div>
                </div>
                <div className="text-center">
                  <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-2">
                    <div className="w-4 h-4 bg-blue-500 rounded-full"></div>
                  </div>
                  <div className="text-sm font-medium">数据库</div>
                  <div className="text-xs text-blue-600">连接正常</div>
                </div>
                <div className="text-center">
                  <div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto mb-2">
                    <div className="w-4 h-4 bg-purple-500 rounded-full"></div>
                  </div>
                  <div className="text-sm font-medium">缓存系统</div>
                  <div className="text-xs text-purple-600">运行良好</div>
                </div>
                <div className="text-center">
                  <div className="w-16 h-16 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-2">
                    <div className="w-4 h-4 bg-amber-500 rounded-full"></div>
                  </div>
                  <div className="text-sm font-medium">API服务</div>
                  <div className="text-xs text-amber-600">响应正常</div>
                </div>
              </div>
            </div>
          </div>
        </Modal>
      </div>
    </AdminLayout>
  )
}